#!/bin/bash

# Chrome网络问题修复脚本
# 解决Ubuntu下Chrome卡顿、下载中断、网页刷新问题

echo "=== Ubuntu Chrome网络问题修复工具 ==="
echo "正在诊断并修复网络问题..."

# 检查是否为root用户
if [[ $EUID -eq 0 ]]; then
   echo "请不要以root身份运行此脚本"
   exit 1
fi

# 1. 更新Chrome到最新版本
echo "1. 更新Chrome浏览器..."
wget -q -O - https://dl.google.com/linux/linux_signing_key.pub | sudo apt-key add - 2>/dev/null
echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" | sudo tee /etc/apt/sources.list.d/google-chrome.list >/dev/null
sudo apt update >/dev/null 2>&1
sudo apt install google-chrome-stable -y

# 2. 修复DNS配置
echo "2. 修复DNS配置..."
CONNECTION_NAME="11-706"
if nmcli connection show | grep -q "$CONNECTION_NAME"; then
    sudo nmcli connection modify "$CONNECTION_NAME" ipv4.dns "8.8.8.8 8.8.4.4"
    sudo nmcli connection down "$CONNECTION_NAME" >/dev/null 2>&1
    sudo nmcli connection up "$CONNECTION_NAME" >/dev/null 2>&1
    echo "✓ DNS已更新为Google DNS"
else
    echo "⚠ 未找到连接 '$CONNECTION_NAME'，请手动配置DNS"
fi

# 3. 调整网络设置
echo "3. 优化网络设置..."
sudo sysctl -w net.ipv6.conf.all.disable_ipv6=1 2>/dev/null
sudo sysctl -w net.ipv6.conf.default.disable_ipv6=1 2>/dev/null
sudo sysctl -w net.core.rmem_max=16777216 2>/dev/null
sudo sysctl -w net.core.wmem_max=16777216 2>/dev/null
sudo sysctl -w net.ipv4.tcp_rmem="4096 87380 16777216" 2>/dev/null
sudo sysctl -w net.ipv4.tcp_wmem="4096 65536 16777216" 2>/dev/null

# 4. 更新无线网卡驱动
echo "4. 更新无线网卡驱动..."
sudo apt install linux-firmware -y

# 5. 创建优化的Chrome启动脚本
echo "5. 创建优化启动脚本..."
cat > ~/chrome_optimized.sh << 'CHROME_EOF'
#!/bin/bash
google-chrome \
    --disable-gpu \
    --disable-software-rasterizer \
    --disable-extensions \
    --disable-plugins \
    --disable-background-timer-throttling \
    --disable-renderer-backgrounding \
    --disable-features=TranslateUI \
    --no-sandbox \
    --disable-setuid-sandbox \
    --disable-dev-shm-usage \
    --disable-accelerated-2d-canvas \
    --no-first-run \
    --disable-default-apps \
    --disable-sync
CHROME_EOF

chmod +x ~/chrome_optimized.sh

# 6. 测试网络连接
echo "6. 测试网络连接..."
if ping -c 2 8.8.8.8 >/dev/null 2>&1; then
    echo "✓ 网络连接正常"
else
    echo "⚠ 网络连接可能存在问题"
fi

echo ""
echo "=== 修复完成 ==="
echo "Chrome版本: $(google-chrome --version 2>/dev/null || echo '未找到Chrome')"
echo ""
echo "使用方法:"
echo "1. 重启系统以应用所有更改"
echo "2. 使用优化脚本启动Chrome: ~/chrome_optimized.sh"
echo "3. 或使用普通Chrome: google-chrome"
echo ""
echo "如果问题仍然存在，请尝试:"
echo "- 重启路由器"
echo "- 更换WiFi频道到5GHz"
echo "- 检查防火墙设置"